import { Component, Injector, ViewEncapsulation, ViewChild , OnInit} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Http } from '@angular/http';
import { UserServiceProxy, UserListDto, EntityDtoOfInt64 } from '@shared/service-proxies/service-proxies';
import { AppConsts } from '@shared/AppConsts';

import { AppComponentBase } from '@shared/app-component-base';
import { TokenAuthServiceProxy } from '@shared/service-proxies/service-proxies';
import { CreateOrEditUserModalComponent } from './create-or-edit-user-modal.component';
// import { EditUserPermissionsModalComponent } from './edit-user-permissions-modal.component';
import { ImpersonationService } from './impersonation.service';

@Component({
    templateUrl: './users.component.html',
    encapsulation: ViewEncapsulation.None
})
export class UsersComponent extends AppComponentBase implements OnInit {

    // Filters
    advancedFiltersAreShown = false;
    filterText = '';
    selectedPermission = '';
    role: number = undefined;


    dataTable = {
        pageIndex: 1,
        pageSize: 10,
        total: 200,
        list: []
    };

    loading = false;
    args: any = { };
    _indeterminate = false;
    _allChecked = false;

    constructor(
        injector: Injector,
        public _impersonationService: ImpersonationService,
        private _http: Http,
        private _userServiceProxy: UserServiceProxy,
        private _tokenAuth: TokenAuthServiceProxy,
        private _activatedRoute: ActivatedRoute
    ) {
        super(injector);
        this.filterText = this._activatedRoute.snapshot.queryParams['filterText'] || '';
    }

    getUsers(pageIndex?: number) {

        if (typeof pageIndex !== 'undefined') {
            this.dataTable.pageIndex = pageIndex || 1;
        }
        
        this._userServiceProxy.getUsers(
            this.filterText,
            this.permission ? this.selectedPermission : undefined,
            this.role,
            '',
            this.dataTable.pageSize,
           (this.dataTable.pageIndex - 1) * this.dataTable.pageSize
        ).subscribe(result => {
            console.log(result);
            this.dataTable.total = result.totalCount;
            this.dataTable.list = result.items;
        });
    }

    unlockUser(record): void {
        this._userServiceProxy.unlockUser(new EntityDtoOfInt64({ id: record.id })).subscribe(() => {
            this.notify.success(this.l('UnlockedTheUser', record.userName));
        });
    }

    getRolesAsString(roles): string {
        let roleNames = '';

        for (let j = 0; j < roles.length; j++) {
            if (roleNames.length) {
                roleNames = roleNames + ', ';
            }

            roleNames = roleNames + roles[j].roleName;
        }

        return roleNames;
    }

    ngOnInit() {
        this.getUsers();
    }

    exportToExcel(): void {
        this._userServiceProxy.getUsersToExcel()
            .subscribe(result => {
           //     this._fileDownloadService.downloadTempFile(result);
            });
    }

    createUser(id?: number): void {
        
        this.showModal(CreateOrEditUserModalComponent,{
            id : id
        }, () => {
            this.getUsers();
        });

      //  this.createOrEditUserModal.show();
    }

    deleteUser(user: UserListDto): void {
        if (user.userName === AppConsts.userManagement.defaultAdminUserName) {
            this.message.warn(this.l('{0}UserCannotBeDeleted', AppConsts.userManagement.defaultAdminUserName));
            return;
        }

        this.message.confirm(
            this.l('UserDeleteWarningMessage', user.userName),
            (isConfirmed) => {
                if (isConfirmed) {
                    this._userServiceProxy.deleteUser(user.id)
                        .subscribe(() => {
                            this.getUsers();
                            this.notify.success(this.l('SuccessfullyDeleted'));
                        });
                }
            }
        );

    }
}
